﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace QuickStart.HotKey
{
    class HotKeyFilter : IMessageFilter
    {

        public HotKeyFilter()
        {
         
        }

        public event HotKeyEventHandler HotKeyPressed;




        #region DLL Import

        /// <summary>
        /// Registers a system hot key.
        /// </summary>
        /// <param name="hWnd">Handle of the window.</param>
        /// <param name="id">Hot key identifier.</param>
        /// <param name="fsModifiers">Key modifiers.</param>
        /// <param name="vk">Virtual key code.</param>
        /// <returns></returns>
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern bool RegisterHotKey(
            IntPtr hWnd,
            int id,
            uint fsModifiers,
            Keys vk
        );

        /// <summary>
        /// Unregisters a system hot key.
        /// </summary>
        /// <param name="hWnd">Handle of the window.</param>
        /// <param name="id">Hot key identifier.</param>
        /// <returns></returns>
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern bool UnregisterHotKey(
            IntPtr hWnd,
            int id
        );

        #endregion



        #region IMessageFilter Members

      

        public bool PreFilterMessage(ref Message m)
        {
            if (m.Msg == 0x0312) //WM_HOTKEY
            {
                KeyModifiers modifiers = GetModifiers(m.LParam);
                Keys key = GetKey(m.LParam);
                int sid = m.WParam.ToInt32();

                HotKeyEventArgs e = new HotKeyEventArgs(modifiers,key,sid);
                
                OnHotKeyPressed(e);
              
            }

            
            return false;
        }
        #endregion     
   
        private void OnHotKeyPressed(HotKeyEventArgs e)
        {
            if (HotKeyPressed != null) HotKeyPressed(this, e);
        }

        Keys GetKey(IntPtr lparam)
        {
            return (Keys)(((int)lparam >> 16) & 0xFFFF);
        }
        KeyModifiers GetModifiers(IntPtr lparam)
        {
            KeyModifiers modifier = (KeyModifiers)((int)lparam & 0xFFFF);
            return modifier;
        }
    }
}
